<style lang="less">
    @import './preview.less';
</style>
<template>
  <div class="preview-container">
    <table class="preview-table" v-if="data.modeltestflag!=='false'">
      <tr>
        <td colspan="6">{{papers.testinfo[0].testtitle}}</td>
      </tr>
      <tr>
        <td>总分</td>
        <td>{{papers.testinfo[0].testnum}}</td>
        <td>出卷人</td>
        <td>{{papers.testinfo[0].creattestpp}}</td>
        <td>出卷时间</td>
        <td>{{papers.testinfo[0].creattesttime}}</td>
      </tr>
      <tr>
        <td>考试时间</td>
        <td colspan="5">{{papers.testinfo[0].teststartdate}} 至 {{papers.testinfo[0].testenddate}} 总计{{papers.testinfo[0].testtimelong}}
          <span style="color: red;">迟到 {{papers.testinfo[0].testlostlong}} 分钟后不能参加考试</span>
        </td>
      </tr>
      <tr v-if="papers.userinfo">
        <td>考生姓名</td>
        <td>{{papers.userinfo.username}}</td>
        <td>考号</td>
        <td>{{papers.userinfo.examnum}}</td>
        <td>得分</td>
        <td>{{papers.userinfo.examusernum}}</td>
      </tr>
      <tr v-if="papers.userinfo">
        <td>交卷时间</td>
        <td colspan="6">{{papers.userinfo.submitdate}}</td>
      </tr>
      <tr v-if="papers.testinfo[0].teststatus === '0'">
        <td colspan="6" >
          <Button type="primary" @click="modifyTestparams()">
              <span>修&nbsp;&nbsp;&nbsp;改&nbsp;&nbsp;&nbsp;参&nbsp;&nbsp;&nbsp;数</span>
          </Button>
        </td>
      </tr>
    </table>

    <!-- 试题本身内容 -->
    <div class="preview-content-container">
      <!-- 每种类型 -->
      <div class="preview-content-type" v-for="(item, index) in papers.tests">
        <p >
          <span>{{index === 0 ? '单选题' : (index === 1 ? '多选题' : '判断题')}}
            <InputNumber v-model="editnum[index]" @on-change="changeTypenum(index)" :step="5" :min="0" :precision="0"
            :disabled="item.length === 0 || papers.testinfo[0].teststatus === '1'"></InputNumber>分
          </span>
          &nbsp;&nbsp;&nbsp;
          <Button type="text" shape="circle" icon="plus-round" @click="addTest(index)"
          v-if="papers.testinfo[0].teststatus === '0'"></Button>
        </p>
        <div class="" v-for="(i, tindex) in item">
          <h2>
            <span>{{getTestIndex(index, tindex)}}.&nbsp;&nbsp;&nbsp;{{i.questitle}}</span>
            <span>(每题 {{i.questionscore}}分 共{{item.length}} 题)</span>
            &nbsp;&nbsp;&nbsp;<Button type="text" shape="circle" icon="android-delete"
            @click="deleteTest(index, tindex)" v-if="papers.testinfo[0].teststatus === '0'"></Button>
          </h2>
          <div style="font-size:18px;">
            <p>A: {{i.quessel1}}</p>
            <p>B: {{i.quessel2}}</p>
            <p v-if="i.quessel3">C: {{i.quessel3}}</p>
            <p v-if="i.quessel4">D: {{i.quessel4}}</p>
            <p v-if="i.quessel5">E: {{i.quessel5}}</p>
            <p v-if="i.quessel6">F: {{i.quessel6}}</p>
            <p v-if="i.quessel7">G: {{i.quessel7}}</p>
            <p v-if="i.quessel8">H: {{i.quessel8}}</p>
            <p v-if="i.quessel9">I: {{i.quessel9}}</p>
          </div>
          <p style="font-size:18px;" v-if="i.newquestionans || i.newquestionans === ''" :class="{cr: i.newquestionans !== i.quesans}">考生答案：{{i.newquestionans}}</p>
          <p style="font-size:18px;">正确答案：{{i.quesans}}</p>
          <p style="font-size:18px;">题目分析：{{i.quesanl}}</p>
        </div>
      </div>
    </div>

    <div class="flex-column-center"  v-if="papers.testinfo[0].teststatus === '0'">
      <Button type="primary" @click="saveModify">保存本次修改</Button>
    </div>


    <!-- <paper-people-set :data="papers.testinfo[0]"></paper-people-set> -->
    <!-- <Button type="primary" @click="goLogin">返回首页</Button> -->
    <!-- <Modal :width="1100" v-model="show" title="考试结果查看" id="caonima">
      <Table :columns="columns1" :data="data1" border></Table>
      <div slot="footer">
      </div>
    </Modal> -->

    <!-- 题目的修改 -->
    <Modal :width="1100" v-model="selectTest" title="增加题目" id="caonima">
      <Row style="margin: 10px 0px;">
        <label>题目</label>
        <Input placeholder="请输题目" clearable style="width: 100px" v-model="testQuestitle"></Input>
        <span style="margin: 0px 10px;">
          <button type="button" class="ivu-btn ivu-btn-primary" @click="searchTest()">
            <i class="ivu-icon ivu-icon-search"></i>
            <span>查询</span>
          </button>
        </span>

        <span style="margin: 0px 10px;" class="fr">
          <button type="button" class="ivu-btn ivu-btn-primary" @click="confirmTest()">
            <Icon type="plus-round"></Icon>
            <span>确认增加</span>
          </button>
        </span>
      </Row>
      <Table :columns="columnsTest" :data="testModel.rows" border @on-selection-change="selected" @on-visible-change="testChange"></Table>
      <Row style="margin: 10px 0px;">
          <Page :total="testModel.count" :page-size="testModel.pageSize" show-elevator style="text-align: center;" @on-change="testLoadPage"></Page>
      </Row>
      <div slot="footer">
      </div>
    </Modal>


    <!-- 考试参数 -->
    <Modal :width="800" v-model="testparamsShow" title="参数修改" @on-visible-change="testparamsChanged">
      <Form ref="formValidate" :model="testparams" :label-width="100">
        <FormItem label="考试名称">
            <Input v-model="testparams.testtitle"  type="text" :rows="4" placeholder="请输入考试名称"></Input>
        </FormItem>
        <FormItem label="交卷后是否可以查看试卷" :label-width="200">
          <RadioGroup v-model="testparams.testflag">
              <Radio label="1">是</Radio>
              <Radio label="0">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="考试时间">
            <DatePicker v-model="testparams.timeing"  type="datetimerange" placeholder="请选择考试时间" style="width: 350px" format="yyyy-MM-dd HH:mm:ss"></DatePicker>
            &nbsp;&nbsp;&nbsp;
            <span>总计时长：{{ getMinute(testparams.timeing[0], testparams.timeing[1]) }}分钟</span>
        </FormItem>
        <FormItem label="禁止登录时间">
          <InputNumber v-model="testparams.testlostlong"  :step="5" :min="0" :precision="0"></InputNumber>
          &nbsp;&nbsp;&nbsp;<span>迟到{{ testparams.testlostlong }}分钟后将不能登录</span>
        </FormItem>
        <FormItem label="考试注意事项">
          <Input v-model="testparams.testinfomation"  type="textarea" :rows="4" placeholder="输入本次考试注意事项..."></Input>
        </FormItem>

      </Form>
      <div slot="footer">
        <Button type="primary" size="large" long  @click="testparamsConfirm()">确定</Button>
      </div>
    </Modal>

  </div>

</template>

<script>
import Cookies from 'js-cookie';
import PagedList from '@/plugins/PagedList.js'
import axios from 'axios'
// import paperPeopleSet from './paper-people-set.vue'

export default {
    name: 'paper-preview',
    props: {
      data: {}
    },
    data () {
      return {
        show: false,
        selectTest: false,
        type: '', // 当前类型， 编辑状体（EDIT），成绩查询(RESULT)，总体成绩预览(ALLRESULT)
        papers: {
          testinfo: [{}],
          tests: []
        },
        columns1: [
          {
              title: '序号',
              type: 'index',
              align: 'center',
              width: 80
          },
            {
                title: '姓名',
                key: 'name',
                align: 'center',
                width: 100
            },
            {
                title: '电话',
                key: 'phone',
                align: 'center',
                width: 120
            },
            {
                title: '身份证号',
                key: 'idcard',
                align: 'center',
                width: 160
            },
            {
                title: '考好',
                key: 'idcard',
                align: 'center',
                width: 160
            },
            {
                title: '得分',
                key: 'defen',
                align: 'center',
                width: 70
            },
            {
                title: '开始答题时间',
                key: 'startTime',
                align: 'center',

            },
            {
                title: '交卷时间',
                key: 'endTime',
                align: 'center',

            }
        ],
        // 增加题目相关参数
        editnum: [0,0,0],
        testModel: new PagedList('rs/sql/singleTable_OrderBy', 10,
        {items: "'*'", tablename: "'questionbank'", orderitem: "'id'"}),
        testQuestitle: '',
        testAddItems: [],
        testIndex: -1,
        columnsTest: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
              title: '上级题库名称',
              key: 'quesparentname',
              align: 'center',
              width: 200
          },
          {
              title: '本级题库名称',
              key: 'quesname',
              align: 'center',
              width: 200
          },
          {
              title: '题目',
              key: 'questitle'
          }
        ],
        // 考试参数设置
        testparamsShow: false,
        testparams: { // 考试参数
          testtitle: '',
          testflag: '',
          timeing: [],
          testlostlong: 0,
          testinfomation: ''
        },
        data1: [
            {
                name: '晚宴阿骨打',
                phone: 18629205383,
                idcard: '610523198905065514',
                testname: 'New York No. 1 Lake Park',
                defen: 100,
                startTime: '2018-05-06 10:00:00',
                endTime: '2018-05-06 11:00:00'
            },

        ]
      }
    },
    mounted () {
      this.papers = Object.assign({}, this.data)
      this.setTypeNum()
    },
    methods: {
      goLogin () {
        Cookies.remove('examinee');
        Cookies.remove('canNumber');
        this.$router.replace({
            name: 'login'
        });
      },
      lookAll () {
        this.show = true
      },

      // 添加题目相关函数
      addTest (index) {
        this.testIndex = index
        this.selectTest = true
        this.searchTest()
      },
      searchTest () {
        let type = '单选题'
        if (this.testIndex === 1) {
          type = '多选题'
        } else if (this.testIndex === 2) {
          type = '判断题'
        }
        let condition = `questype='${type}' `
        if (this.testQuestitle) {
          condition +=  'and ' + this.$getCondition({questitle: this.testQuestitle})
        }
        this.testModel.search(condition)
      },
      testLoadPage (index) {
        this.testModel.loadPage(index)
      },
      selected (arr) {
        this.testAddItems = arr
      },
      confirmTest () {
        // 数组去重
        let arr = [] // 去重后的数组
        let repatArr = [] // 重复的数据
        let oriArr = this.papers.tests[this.testIndex] // 原有的数组
        this.testAddItems.forEach((item) => {
          if (oriArr.length === 0) {
            arr.push(item)
          }
          for (var i = 0; i < oriArr.length; i++) {
            if (item.id === oriArr[i].id) {
              repatArr.push(item)
              break
            }
            if (i === oriArr.length - 1) {
              arr.push(item)
            }
          }
        })
        if (repatArr.length > 0) {
          let mgs = ''
          repatArr.forEach(item => {
            mgs += `${item.questitle},`
          })
          this.$Modal.info({
            title: '去掉重复题目',
            content: `所选择题目中，${mgs}等${repatArr.length}道题已经出现在试卷中，系统自动取消`
          });
        }

        this.papers.tests[this.testIndex].push(...arr)
        this.selectTest = false
        this.modifyTypenum(this.testIndex)
      },
      testChange (val) {
        if (!val) {
          this.testQuestitle = ''
          this.testIndex = -1
          this.testAddItems = []
        }
      },
      // 删除某题
      deleteTest (index, tindex) {
        this.papers.tests[index].splice(tindex, 1)
        this.modifyTypenum(index)
      },
      // 改变每道题的分数
      modifyTypenum (index) {
        // debugger
        let tn = this.editnum[index]/this.papers.tests[index].length
        this.papers.tests[index].forEach(item => {
          item.questionscore = tn
        })
      },
      // 改变总分
      modifyTestnum () {
        let sum = 0
        this.editnum.map((item) => {
          sum += item
        })
        this.papers.testinfo[0].testnum = sum
      },
      changeTypenum (index) {
        this.modifyTypenum(index)
        this.modifyTestnum()
      },
      getTestIndex (index, tindex) {
        if (index === 0) {
          return tindex + 1
        } else if (index === 1) {
          return this.papers.tests[0].length + tindex + 1
        } else if (index === 2) {
          return this.papers.tests[0].length + this.papers.tests[1].length + tindex + 1
        }
      },
      // 设置每种类型题目的分值
      setTypeNum () {
        for (var i = 0; i < 3; i++) {
          if (this.papers.tests && this.papers.tests[i].length > 0) {
            this.editnum[i] = this.papers.tests[i][0].questionscore * this.papers.tests[i].length
          }
        }
      },
      getTesttype () {
        let i = 0
        this.editnum.forEach(item => {
          if (item === 0) {
            i += 1
          }
        })
        if (i === 3) {
          return '无试题'
        }
        if (i === 2) {
          return '单一试题'
        }
        if (i < 2) {
          return '综合试题'
        }
      },
      // 保存修改
      saveModify () {
        if (this.papers.tests[0].length > 0) {
          if (this.papers.tests[0][0].questionscore % 1 !== 0) {
            this.$Modal.info({
              title: '分值异常',
              content: '单选题分值异常，请从新设置分值'
            });
            return
          }

        }
        if (this.papers.tests[1].length > 0) {
          if (this.papers.tests[1][0].questionscore % 1 !== 0) {
            this.$Modal.info({
              title: '分值异常',
              content: '多选题分值异常，请从新设置分值'
            });
            return
          }

        }
        if (this.papers.tests[2].length > 0) {
          if (this.papers.tests[2][0].questionscore % 1 !== 0) {
            this.$Modal.info({
              title: '分值异常',
              content: '判断题分值异常，请从新设置分值'
            });
            return
          }

        }
        // 组织数据
        let obj = {
          oneques: [],
          douques: [],
          judques: [],
          testnum: this.papers.testinfo[0].testnum,
          testid: this.papers.testinfo[0].id,
          testtype: this.getTesttype()
        }

        this.papers.tests[0].forEach((item, index) => {
          obj.oneques.push({testid: item.testid, questionid: item.id, questionnum: this.getTestIndex(0, index), questionscore: item.questionscore})
        })
        this.papers.tests[1].forEach((item, index) => {
          obj.douques.push({testid: item.testid, questionid: item.id, questionnum: this.getTestIndex(1, index), questionscore: item.questionscore})
        })
        this.papers.tests[2].forEach((item, index) => {
          obj.judques.push({testid: item.testid, questionid: item.id, questionnum: this.getTestIndex(2, index), questionscore: item.questionscore})
        })
        // console.log('1111111111111', obj);
        axios.post('rs/logic/changetest', {data: obj}).then(res => {
          if (res.data.code === 200) {
            this.$Message.success({
              content: '修改成功'
            })
          }
        }).catch(error => {
          this.$Message.error({
            content: '修改失败'
          })
        })
      },



      //  考试参数设置
      modifyTestparams () {
        this.testparams = {
          testtitle: this.papers.testinfo[0].testtitle,
          testflag: this.papers.testinfo[0].testflag,
          timeing: [new Date(this.papers.testinfo[0].teststartdate), new Date(this.papers.testinfo[0].testenddate)],
          testlostlong: parseInf(this.papers.testinfo[0].testlostlong),
          testinfomation: this.papers.testinfo[0].testinfomation
        }
        this.testparamsShow = true
      },
      testparamsConfirm () {
        let obj = Object.assign({}, this.papers.testinfo[0], this.testparams)
        obj.teststartdate = this.$formatDateTime(obj.timeing[0]),
        obj.testenddate = this.$formatDateTime(obj.timeing[1]),
        obj.testtimelong = this.getMinute(obj.timeing[0], obj.timeing[1])
        // console.log('1111111111111', obj);
        axios.post('rs/entity/testaper', obj).then(res => {
          this.testparamsShow = false
          this.papers.testinfo[0] = Object.assign({}, this.papers.testinfo[0], this.testparams)
        }).catch((error) => {
          // console.log(error);
          this.$Message.error('保存失败');
        })
      },
      // 窗口关闭后清空参数
      testparamsChanged (val) {
        if (!val) {
          this.testparams = { // 清空参数
            testtitle: '',
            testflag: '',
            timeing: [],
            testlostlong: '',
            testinfomation: ''
          }
        }
      },
      getMinute (start, end) {
        let m = new Date(end).getTime() - new Date(start).getTime()
        return m/1000/60
      }
    },
    watch: {
      'data' () {
        this.papers = Object.assign({}, this.data)
        this.setTypeNum()
      }
    },
    // components: {
    //     paperPeopleSet
    // },
};
</script>
